﻿using UnityEngine;
using System.Collections;

public class RayBoxController : MonoBehaviour {

	private SteamVR_TrackedObject trackedObject;
	private GameObject rayBox;
	private bool dragEnable;
	private Vector3 rayBoxOriginalScale;
	private float currentScale;


	public float scaleSpeed = 1;
	public float maxScale = 2;
	public float minScale = 0.1f;
	public float scaleStep = 0.1f;

	void Awake() {

		currentScale = 1;

		dragEnable = false;

		rayBox = GameObject.Find ("RayBox");
		rayBoxOriginalScale = rayBox.transform.localScale;
		if (rayBox == null) {

			Debug.LogError ("场景中的Volume物体必须命名为RayBox。");

		}

		trackedObject = GetComponent<SteamVR_TrackedObject> ();

	}

	void Update() {

		var device = SteamVR_Controller.Input ((int)trackedObject.index);

		// attach / detach raybox
		if (device.GetTouchDown (SteamVR_Controller.ButtonMask.Trigger)) {
			if(dragEnable) 
				AttachRayBox ();
		} 
		else if (device.GetTouchUp (SteamVR_Controller.ButtonMask.Trigger)) {
			DetachRayBox ();
		}

		// scale control
		if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad)) {

			Vector2 cc = device.GetAxis();

			float angle = Vector2Angle (new Vector2 (1, 0), cc);
			if (angle > 45 && angle < 135) {

				currentScale -= scaleStep;
				if (currentScale < minScale)
					currentScale = minScale;

				Vector3 targetScale = rayBoxOriginalScale * currentScale;

				rayBox.transform.localScale = targetScale;
			} 
			else if (angle < -45 && angle > -135) {

				currentScale += scaleStep;
				if (currentScale > maxScale)
					currentScale = maxScale;

				Vector3 targetScale = rayBoxOriginalScale * currentScale;

				rayBox.transform.localScale = targetScale;
				
			}
		}

	}

	public void EnableDrag(bool enable) {

		dragEnable = enable;

	}

	private void DetachRayBox() {

		rayBox.transform.parent = null;

	}

	private void AttachRayBox() {

		rayBox.transform.parent = transform;
	}

	private float Vector2Angle(Vector2 from, Vector2 to) {
		float angle;
		Vector3 cross = Vector3.Cross (from, to);
		angle = Vector2.Angle (from, to);
		return cross.z > 0 ? -angle : angle;
	}

}
